import util from "../../utils/util.js";
import {
  orderToModel
} from "../../models/orders.js";
Page({
  data: {
    orderList: [],
    coupon_list: ["请选择优惠券"],
    couponId: '',
    index: 0,
    order_id: 0,
    height: 0,
    isShade: true,
    orderOK: true,
    dis_money: 0,
    pay_money: 0
  },
  // 监听页面加载
  onLoad: function (options) {
    this._getOrder(options)
  },
  //生成订单
  submitOrder() {
    console.log(this.data.orderOK)
    //阻止重复提交
    if (!this.data.orderOK) return false;
    this._orderOk(false);
    //开始准备提交
    const index = this.data.index;
    const orderList = this.data.orderList;
    let couponId = ""
    //获取优惠券id
    if (index > 0) {
      couponId = orderList.coupon_list[index - 1].user_cou_id
    }
    orderToModel(index, orderList).then(res => {
      if (res.errorCode == 0) {
        this.setData({
          order_id: res.data.order_id,
          isShade: false,
          height: "750rpx",
          couponId
        });
        console.log("生成订单成功");
      } else {
        console.log("生成订单失败");
        util.showToast('生成订单失败')
      }
      this._orderOk(true);
    });
  },
  //关闭详情
  closeDetail() {
    //更新状态
    this.setData({
      isShade: true,
      height: "0rpx",
      orderOK: true
    });
    //删除已经使用的优惠券
    if (this.data.index > 0) {
      this.delCoupon()
    }
  },
  //删除已经使用过的优惠券
  delCoupon() {
    let orderList = this.data.orderList
    let coupon_list = ['请选择优惠券']
    // 通过优惠券id获取优惠券下标
    let num = orderList.coupon_list.findIndex(item => {
      return item.user_cou_id == this.data.couponId
    })
    orderList.coupon_list.splice(num, 1)
    orderList.coupon_list.forEach(element => {
      coupon_list.push(element.title);
    });
    orderList.dis_money = this.data.dis_money
    orderList.pay_money = this.data.pay_money
    this.setData({
      orderList,
      coupon_list,
      index: 0
    })
  },
  //选择优惠券
  paySelect(event) {
    const orderList = this.data.orderList
    const index = (+event.detail.value) || 0
    console.log(typeof index)
    console.log(orderList.coupon_list)
    const coupinMoney = index > 0 ? parseFloat(orderList.coupon_list[index - 1].money) : 0
    orderList.dis_money = (this.data.dis_money + coupinMoney).toFixed(2)
    orderList.pay_money = (this.data.pay_money - coupinMoney).toFixed(2)
    this.setData({
      index,
      orderList
    });
    console.log(this.data.orderList)
  },
  //获取预油品订单
  _getOrder(options) {
    const orderList = JSON.parse(options.item);
    const dis_money = parseFloat(orderList.dis_money)
    const pay_money = parseFloat(orderList.pay_money)
    let coupon_list = ["请选择优惠券"];
    orderList.coupon_list.forEach(element => {
      coupon_list.push(element.title);
    });
    console.log(orderList);
    this.setData({
      orderList,
      coupon_list,
      dis_money,
      pay_money
    });
  },
  _orderOk(state) {
    this.setData({
      orderOK: state
    });
  },
  // 分享
  onShareAppMessage() {}
});